import React, { useState } from 'react';
import { Card, message, Row, Col, Typography, Spin } from 'antd';
import { ProductForm } from '@/components';
import { productService } from '@/services';
import { ProductFormData } from '@/types';
import { useNavigate, useSearchParams } from '@umijs/max';

const { Title } = Typography;

const ProductPublish: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const editProductId = searchParams.get('edit');
  
  const handleSubmit = async (formData: ProductFormData) => {
    try {
      setLoading(true);
      
      if (editProductId) {
        // 编辑商品
        await productService.updateProduct(editProductId, formData);
        message.success('商品编辑成功！');
      } else {
        // 发布新商品
        await productService.createProduct(formData);
        message.success('商品发布成功！');
      }
      
      navigate('/products/list');
    } catch (error) {
      message.error(editProductId ? '商品编辑失败' : '商品发布失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    navigate('/products/list');
  };

  const [initialData, setInitialData] = useState<ProductFormData | undefined>(undefined);

  // 如果是编辑模式，加载商品数据
  React.useEffect(() => {
    if (editProductId) {
      loadProductData();
    }
  }, [editProductId]);

  const loadProductData = async () => {
    if (!editProductId) return;
    
    try {
      setLoading(true);
      const product = await productService.getProduct(editProductId);
      if (product) {
        setInitialData({
          title: product.title,
          category: product.category,
          price: product.price,
          originalPrice: product.originalPrice,
          condition: product.condition,
          description: product.description,
          images: product.images,
          tags: product.tags,
          tradeMethod: product.tradeMethod,
          location: product.location,
          school: product.school,
          campus: product.campus
        });
      }
    } catch (error) {
      message.error('加载商品数据失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-4 md:p-6 bg-gray-50 min-h-screen">
      {/* 页面标题 */}
      <div className="mb-6 text-center">
        <Title level={2} className="text-2xl md:text-3xl font-bold text-gray-900">
          {editProductId ? '编辑商品' : '发布新商品'}
        </Title>
        <p className="text-gray-600 text-sm md:text-base">
          {editProductId ? '修改商品信息，让您的闲置物品找到新主人' : '填写商品信息，让您的闲置物品找到新主人'}
        </p>
      </div>

      <Row justify="center">
        <Col xs={24} sm={22} md={20} lg={18} xl={16} xxl={14}>
          {loading ? (
            <div className="flex justify-center py-20">
              <Spin size="large" />
            </div>
          ) : (
            <ProductForm
              initialData={initialData}
              onSubmit={handleSubmit}
              onCancel={handleCancel}
              isEdit={!!editProductId}
            />
          )}
        </Col>
      </Row>
    </div>
  );
};

export default ProductPublish;